package com.qf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author zdl
 * @date 2025/2/8
 */
@RestController
@RequestMapping("/upload")
public class UploadController {
    private static final String UPLOAD_DIR = "D:/test/a/";  // 图片保存路径

    // 文件上传接口
    @PostMapping("/image")
    public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 判断上传的文件是否为空
        if (file.isEmpty()) {
            return "文件为空，上传失败";
        }

        // 获取文件名并创建目标文件路径
        String fileName = file.getOriginalFilename();
        Path uploadPath = Paths.get(UPLOAD_DIR + fileName);

        // 确保目标目录存在
        Files.createDirectories(uploadPath.getParent());

        // 保存文件到本地
        file.transferTo(uploadPath);

        // 构建图片的访问 URL 路径
        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/uploads/" + fileName)  // 使用正确的相对路径
                .toUriString();
        System.out.println(fileDownloadUri);
        // 返回图片的 URL 地址，前端可以通过这个 URL 显示图片
        return fileDownloadUri;
    }

    // 提供图片访问接口
    //todo 回显404
    @GetMapping("/uploads/{fileName}")
    @ResponseBody
    public byte[] getImage(@PathVariable String fileName) throws IOException {
        Path filePath = Paths.get(UPLOAD_DIR + fileName);  // 根据文件名找到文件路径
        System.out.println(filePath);
        return Files.readAllBytes(filePath);  // 读取文件并返回
    }

}
